package com.itheima.mongo.api;

import com.itheima.dubbo.api.FriendApi;
import com.itheima.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long friendId) {
        //因为需要双向绑定,所以需要绑定两次
        //保存自己的好友数据
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        boolean exists1 = mongoTemplate.exists(query1, Friend.class);
        if (!exists1) {
            Friend friend1 = new Friend();
            friend1.setFriendId(friendId);
            friend1.setUserId(userId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
        //保存好友的数据
        Query query2 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        boolean exists2 = mongoTemplate.exists(query2, Friend.class);
        if (!exists2) {
            Friend friend2 = new Friend();
            friend2.setFriendId(friendId);
            friend2.setUserId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    @Override
    public List<Friend> findByFriend(Long id, Integer page, Integer pagesize) {
        //构造分页条件
        Criteria criteria = Criteria.where("userId").is(id);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        return list;
    }

    @Override
    public void delete(Long userId, Long friendId) {
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        //判断是否存在
        boolean exists1 = mongoTemplate.exists(query1, Friend.class);
        if (exists1) {
            Friend one = mongoTemplate.findOne(query1, Friend.class);
            mongoTemplate.remove(one);
        }

        Query query2 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        //判断是否存在
        boolean exists2 = mongoTemplate.exists(query2, Friend.class);
        if (exists2) {
            Friend one = mongoTemplate.findOne(query2, Friend.class);
            mongoTemplate.remove(one);
        }
    }
}
